package org.ciallo.simplemusicplayer.data;

import android.content.Context;
import androidx.room.Database;
import androidx.room.Room;
import androidx.room.RoomDatabase;
import org.ciallo.simplemusicplayer.data.dao.*;
import org.ciallo.simplemusicplayer.data.model.*;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @author Jukomu
 * @Description: 应用的 Room 数据库类
 * 采用单例模式
 * @Package: org.ciallo.simplemusicplayer.data
 * @Project: SimpleMusicPlayer
 * @name: AppDatabase
 * @Date: 2025/5/29-05:11
 * @Filename: AppDatabase
 */
@Database(entities = {Song.class, FavoriteSong.class, Playlist.class, PlaylistSongCrossRef.class, RecentlyPlayedSong.class, PlayCount.class},
        version = 6,
        exportSchema = false)
public abstract class AppDatabase extends RoomDatabase {

    // 定义DAO的抽象方法
    public abstract SongDao songDao();
    public abstract FavoriteSongDao favoriteSongDao();
    public abstract PlaylistDao playlistDao();
    public abstract RecentlyPlayedDao recentlyPlayedDao();
    public abstract PlayCountDao playCountDao();

    private static volatile AppDatabase INSTANCE; // 单例实例
    private static final int NUMBER_OF_THREADS = 4; // 数据库操作线程池大小

    // 用于执行数据库写操作的线程池
    public static final ExecutorService databaseWriteExecutor =
            Executors.newFixedThreadPool(NUMBER_OF_THREADS);

    /**
     * 获取数据库的单例。
     * @param context Application context.
     * @return AppDatabase 的单例实例。
     */
    public static AppDatabase getDatabase(final Context context) {
        if (INSTANCE == null) {
            synchronized (AppDatabase.class) {
                if (INSTANCE == null) {
                    INSTANCE = Room.databaseBuilder(context.getApplicationContext(),
                                    AppDatabase.class, "simple_music_player_db")
                            // 由于添加了新表，如果已有旧数据库，需要迁移或允许破坏性迁移
                            .fallbackToDestructiveMigration() // 开发阶段简单处理
                            // 对于版本2，如果你想保留旧数据，需要添加从版本1到版本2的 Migration
                            // .addMigrations(MIGRATION_1_2)
                            .build();
                }
            }
        }
        return INSTANCE;
    }

    // (可选) 数据库创建时的回调，可以用来预填充数据等
    /*
    private static RoomDatabase.Callback sRoomDatabaseCallback = new RoomDatabase.Callback() {
        @Override
        public void onCreate(@NonNull SupportSQLiteDatabase db) {
            super.onCreate(db);
            // 例如：预填充一些数据
            // databaseWriteExecutor.execute(() -> {
            //    FavoriteSongDao dao = INSTANCE.favoriteSongDao();
            //    dao.addFavorite(new FavoriteSong(123L, System.currentTimeMillis()));
            // });
        }
    };
    */
}
